<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <div class="left-searchBox">
          <el-input
            v-model="searchVal"
            style="margin-bottom: 10px"
            type="text"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="输入员工姓名全员搜索"
            @input="onSearch"
          />
        </div>
        <div class="left-treeBox">
          <el-tree
            ref="tree"
            node-key="id"
            default-expand-all
            :data="treeListData"
            :props="defaultProps"
            :expand-on-click-node="false"
            highlight-current
          />
        </div>
      </div>
      <div class="right">
        <el-row type="flex" justify="end" class="operate-tools">
          <el-button size="mini" type="primary" @click="$router.push({ path: '/staff/detail'})">添加员工</el-button>
          <el-button size="mini" @click="importVisible = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <el-table :data="tableListData">
          <el-table-column label="头像">
            <template slot-scope="scope">
              <el-avatar
                v-if="scope.row.staffPhoto"
                :src="scope.row.staffPhoto"
              />
              <el-avatar v-else class="username">{{
                scope.row.username.charAt(0)
              }}</el-avatar>
            </template>
          </el-table-column>
          <el-table-column align="center" label="名称" prop="username" />
          <el-table-column align="center" label="手机号" prop="mobile" />
          <el-table-column align="center" label="工号" prop="workNumber" />
          <el-table-column
            align="center"
            label="聘用形式"
            prop="formOfEmployment"
          >
            <template #default="{ row }">
              <span>{{ row.formOfEmployment ? "正式" : "试用" }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="部门" prop="departmentName" />
          <el-table-column align="center" label="入职时间" prop="timeOfEntry" />
          <el-table-column align="center" label="操作">
            <template #default="{ row }">
              <el-button type="text" @click="viewDetails(row)">查看</el-button>
              <el-button
                type="text"
                @click="rolePerception(row)"
              >角色</el-button>
              <el-button type="text" @click="delEmployee(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" align="middle" justify="end" style="height: 60">
          <el-pagination
            :page-size="paging.pageSize"
            :page-count="paging.total"
            :pager-count="7"
            :current-page="paging.page"
            layout="total, prev, pager, next"
            :total="paging.total"
            @current-change="pageChange"
          />
        </el-row>
      </div>
    </div>
    <permission-dialog
      :visible.sync="permissionVisible"
      :checkout-data.sync="checkoutData"
      :role-ids.sync="roleIds"
      @confirm="confirm"
      @pushRoleIds="pushRoleIds"
    />
    <import-dialog :visible.sync="importVisible" />
  </div>
</template>
<script>

import FileSaver from 'file-saver'
import { assignRolesAPI, getUserInformation, deleteEmployeeAPI, exportUsersAPI, getEmployeeAPI } from '@/api/staff'
import { enabledRoleList } from '@/api/role'
import { getDepartmentAPI } from '@/api/department'
import { list2Tree } from '@/utils/tree'
import importDialog from './components/import-dialog.vue'
import PermissionDialog from './components/permission-dialog.vue'
export default {
  name: 'Staff',
  components: { importDialog, PermissionDialog },
  data() {
    return {
      // 分页请求数据
      paging: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      // 表格数据
      tableListData: [],
      // 树形控件数据
      treeListData: [],
      // 树形控件配置
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 权限弹窗开关
      permissionVisible: false,
      // 权限弹窗id
      permissionId: '',
      // 导入弹窗开关
      importVisible: false,
      // 分配角色弹窗
      checkoutData: [],
      // // 角色id
      roleIds: [],
      // 搜索框数据
      searchVal: '',
      // 搜索延时器
      timer: null
    }
  },
  created() {
    this.tableData()
    this.treeData()
  },
  methods: {
    // 树形控件数据
    async treeData() {
      const { data } = await getDepartmentAPI()
      this.treeListData = list2Tree(data, 0)
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.treeListData[0].id)
      })
    },
    // 列表数据
    async tableData() {
      const { data } = await getEmployeeAPI(this.paging, this.searchVal)
      this.tableListData = data.rows
      this.paging.total = data.total
    },
    // 分页按钮触发执行
    pageChange(page) {
      this.paging.page = page
      !this.tableListData.length && this.paging.page--
      !this.paging.page && this.paging.page++
      this.tableData()
    },
    // 查看员工详情
    viewDetails({ id }) {
      this.$router.push({
        path: '/staff/detail/' + id
      })
    },
    // 角色权限
    async rolePerception({ id }) {
      const res = await getUserInformation(id)
      const { data } = await enabledRoleList()
      this.checkoutData = data
      this.roleIds = res.data.roleIds
      this.permissionId = id
      this.permissionVisible = true
    },
    // 删除员工
    async delEmployee({ id }) {
      await this.$confirm('将会永久删除文件， 确定吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await deleteEmployeeAPI(id)
      this.tableData()
    },
    // 搜索
    // 1. 搜索功能设置防抖， 防抖是减缓触发频率的一种方法，
    // 2. 输入框监听input事件
    // 3. 防抖后， 获取数据
    onSearch() {
      // 实现防抖
      // 1. 声明一个存放延时器的变量
      // 2. 每次onSearch执行的时候， 先清除延时器
      // 3. 再重新设置延时器
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.tableData()
      }, 1000)
    },
    // 导出excel
    async exportExcel() {
      const res = await exportUsersAPI()
      // 导出的是blob对象， 需要用到file-saver插件
      FileSaver.saveAs(res, '员工数据.xlsx')
    },
    // dialog确认
    confirm() {
      const result = this.roleIds.join(',').split(',')
      assignRolesAPI(this.permissionId + '', result)
    },
    // 角色id数组
    pushRoleIds(value) {
      this.roleIds.push(value.pop())
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 330px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
    height: 845.4px;
    .left-searchBox {
      display: block;
    }
    .left-treeBox {
      overflow-y: auto;
      height: 805.4px;
      &::-webkit-scrollbar {
        width: 0;
        display: none;
      }

      &::-webkit-scrollbar-track {
        background-color: #f5f5f5;
      }

      &::-webkit-scrollbar-thumb {
        background-color: skyblue;
        border-radius: 5px;
      }
    }
  }
  .right {
    flex: 1;
    padding: 20px;

    .operate-tools {
      margin: 10px;
    }
    .username {
      display: inline-block;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      text-align: center;
      color: #fff;
      font-weight: bold;
      background: #04c9be;
      width: 40px;
      height: 40px;
      line-height: 40px;
      font-size: 14px;
    }
  }
}

::v-deep .el-scrollbar__view.el-select-dropdown__list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
::v-deep .el-input--suffix .el-input__inner {
  width: 330px;
}
</style>
